<template>
  <ContentLayout>
    <SearchBox :title="'任务管理'" @handleQuery="handleQuery" @resetQuery="resetQuery">
      <template slot="form">
        <el-form class="search-form" ref="searchForm" :model="searchForm" label-width="auto" size="medium">
          <el-form-item label="任务编号">
            <el-input v-model="searchForm.code" placeholder="请输入策略编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="任务名称">
            <el-input v-model="searchForm.title" placeholder="请输入策略名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="任务优先级">
            <el-select style="display: block" v-model="searchForm.level" placeholder="请选择任务优先级" clearable>
              <el-option v-for="item in levelList" :key="item.k" :label="item.v" :value="item.k"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务模块类型">
            <el-select style="display: block" v-model="searchForm.busSource" placeholder="请选择任务模块类型" clearable>
              <el-option v-for="item in busSourceList" :key="item.k" :label="item.v" :value="item.k"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </SearchBox>

    <EvTable
      v-if="isShowTable"
      ref="table"
      :options="{
        data,
        columns,
        ...defaultOptions,
      }"
      :showPage="true"
      :tablePage="page"
      @handlePageChange="handlePageChange"
    >
      <template #toolbar_buttons>
        <EvButton icon="el-icon-plus" power="customer_insert" type="primary" @click="handleAdd">添加</EvButton>
        <EvButton icon="el-icon-plus" type="primary" plain @click="start">启动</EvButton>
        <EvButton icon="el-icon-plus" type="primary" plain @click="complete">完成</EvButton>
        <EvButton icon="el-icon-edit" type="primary" plain @click="receive">领用</EvButton>
        <EvButton icon="el-icon-edit" type="primary" plain @click="distribution">指派</EvButton>
        <EvButton icon="el-icon-delete" type="info" @click="deleteTasks">删除</EvButton>
      </template>
      <template #toolbar_tools>
        <vxe-button icon="vxe-icon-download" circle title="甘特图" @click="isShowTable = false"></vxe-button>
      </template>
      <template #operation_default="{ scope }">
        <el-button type="text" @click="edit(scope)" :disabled="scope.row.state == '完成'">编辑</el-button>
        <el-button type="text" @click="see(scope)">详情</el-button>
      </template>
      <template #status_default="{ scope }">
        <div :class="['status-item', getStatusName(scope.row.state)]">
          {{ scope.row.state }}
        </div>
      </template>
      <template #template_point="{ scope }">
        <el-progress
          color="#46be64"
          :stroke-width="10"
          :percentage="scope.row.point ? Math.floor(scope.row.point) : 0"
        ></el-progress>
      </template>
    </EvTable>
    <gantt
      v-else
      ref="childGantt"
      height="650"
      :isConfigArea="false"
      :isFullScreen="true"
      :ganttCondition="ganttCondition"
    ></gantt>
    <!-- 选择人员 -->
    <PersonReceive ref="personReceive" @handleSelectBack="personSelectBack"></PersonReceive>
    <!-- 编辑详情 -->
    <taskDetail ref="taskDetail" @handleConfirm="handleQuery"></taskDetail>
  </ContentLayout>
</template>
  <script>
import ContentLayout from "@/layout/contentLayout.vue";
import SearchBox from "@/components/EvTable/searchBox.vue";
import taskDetail from "./detail.vue";
import PersonReceive from "./personReceive.vue";
import gantt from "./gantt.vue";
export default {
  components: {
    ContentLayout,
    SearchBox,
    taskDetail,
    PersonReceive,
    gantt,
  },
  provide() {
    return {
      microservices: this.microservices,
      resource: this.resource,
      busSource: this.busSource,
    };
  },
  data() {
    return {
      /* 搜索项表单 */
      searchForm: {
        name: null,
        code: null,
      },
      isShowTable: true,
      microservices: "function-manufacture-data",
      resource: "TaskManage",
      busSource: "workOrder",
      commonSearch: null,
      defaultSort: "insertTime desc",
      /* 任务状态枚举 */
      statusEnums: [
        { name: "未开始", value: "INFO" },
        { name: "启动", value: "NORMAL" },
        { name: "已下发", value: "NORMAL" },
        { name: "执行中", value: "NORMAL" },
        { name: "暂停", value: "WARNING" },
        { name: "中止", value: "DANGER" },
        { name: "完成", value: "SUCCESS" },
      ],
      selectRecords: [],
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      columns: [
        { type: "checkbox", fixed: "left", align: "center", width: 50 },
        { title: "序号", align: "center", width: 60, type: "seq" },
        { title: "任务编号", field: "code", align: "left", width: 200 },
        { title: "任务名称", field: "title", align: "left", width: 200 },
        { title: "状态", field: "state", align: "center", slots: { default: "status_default" }, width: 100 },
        { title: "任务类别", field: "busSource", align: "center", width: 120 },
        {
          title: "优先级",
          field: "level",
          align: "center",
          minWidth: 80,
          width: 100,
        },
        {
          title: "完成进度",
          field: "point",
          slots: { default: "template_point" },
          width: 180,
        },
        { title: "创建时间", field: "insertTime", align: "center", formatter: "formatTime", width: 150 },
        { title: "计划开始时间", field: "planBegin", align: "center", formatter: "formatTime", width: 150 },
        { title: "计划结束时间", field: "planEnd", align: "center", formatter: "formatTime", width: 150 },
        { title: "实际开始时间", field: "beginTime", align: "center", formatter: "formatTime", width: 150 },
        { title: "实际结束时间", field: "endTime", align: "center", formatter: "formatTime", width: 150 },
        {
          title: "操作",
          field: "table_operate",
          fixed: "right",
          align: "left",
          width: 100,
          resizable: false,
          slots: { default: "operation_default" },
        },
      ],
      data: [],
      busSourceList: [],
      levelList: [],
      defaultOptions: {
        toolbarConfig: {
          slots: {
            tools: "toolbar_tools",
          },
        },
      },
      ganttCondition: {
        AND: [
          ["isDelete", "=", 0],
          // ['busSource', 'IN', ['workOrder', 'process']]
        ],
      },
    };
  },
  created() {
    this.loadData();
  },
  mounted() {
    this.getDictionarys();
  },
  methods: {
    getDictionarys() {
      let titles = "任务优先级,任务业务模块类型";
      this.$server()
        .batchQueryDictionary(titles)
        .then((response) => {
          this.levelList = response.filter((f) => f.title === "任务优先级")[0].details;
          this.busSourceList = response.filter((f) => f.title === "任务业务模块类型")[0].details;
        })
        .catch((response) => {
          this.$message.error(response.data.message);
        });
    },
    handleAdd() {
      const params = {
        drawerTitle: "添加",
        disabled: false,
      };
      this.$refs.taskDetail.open(params, null);
    },
    edit(scope) {
      const params = {
        drawerTitle: "编辑",
        disabled: false,
      };
      this.$refs.taskDetail.open(params, scope.row.id);
    },
    see(scope) {
      const params = {
        drawerTitle: "查看",
        disabled: true,
      };
      this.$refs.taskDetail.open(params, scope.row.id);
    },
    clearCheck() {
      this.$refs.table.changeAllEvent();
      this.selectRecords = [];
    },
    // 执行搜索
    handleQuery() {
      this.page.currentPage = 1;
      this.loadData();
    },
    resetQuery() {
      this.searchForm = {
        name: null,
        code: null,
      };
      this.page.currentPage = 1;
      this.loadData();
    },
    // 获取状态名称
    getStatusName(property) {
      return "status-" + this.statusEnums.find((item) => item.name === property)?.value;
    },
    // 加载数据
    loadData() {
      let params = [];
      Object.keys(this.searchForm).forEach((el) => {
        if (this.searchForm[el]) {
          params.push([el, "LIKE", `%${this.searchForm[el]}%`]);
        }
      });
      if (params.length > 0) {
        this.commonSearch = { AND: [...params] };
      } else {
        this.commonSearch = null;
      }
      let condition = null;
      if (this.commonSearch && JSON.stringify(this.commonSearch) != "{}") {
        let common = JSON.parse(JSON.stringify(this.commonSearch));
        if (!condition) {
          condition = { AND: [] };
        }
        condition.AND = [...condition.AND, ...common.AND];
      }
      this.$server()
        .query(
          this.microservices,
          this.resource,
          condition,
          this.defaultSort,
          { current: this.page.currentPage, size: this.page.pageSize },
          true
        )
        .then((response) => {
          this.page.total = response.total;
          this.data = response.list;
        })
        .catch((response) => {
          this.$message.error(response.data.message);
        });
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage;
      this.page.pageSize = pageSize;
      this.loadData();
    },
    // 启用任务
    start() {
      this.selectRecords = this.$refs.table.getSelectRecords();
      if (this.selectRecords && this.selectRecords.length == 0) {
        this.$message.warning(this.$t("common.common_unselect_data"));
        return;
      }
      const isHasComplete = this.selectRecords.every((item) => {
        return item.state == "未开始";
      });
      if (!isHasComplete) {
        this.$message.warning("只有未开始的任务才能进行启用操作，请检查并重新勾选");
        return;
      }

      this.$confirm("是否将选中的任务启动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [];
        ids = this.selectRecords.map((item) => {
          return item.id;
        });
        this.$server()
          .erdfRequest(`/server/${this.microservices}/base/${this.resource}/updateTaskState`, [ids, "execute"], "POST")
          .then(() => {
            this.$message.success("已启动");
            this.loadData();
            this.clearCheck();
          })
          .catch((response) => {
            this.$message.error(response.data.message);
          });
      });
    },
    // 完成任务
    complete() {
      this.selectRecords = this.$refs.table.getSelectRecords();
      if (this.selectRecords && this.selectRecords.length == 0) {
        this.$message.warning(this.$t("common.common_unselect_data"));
        return;
      }

      const isHasComplete = this.selectRecords.every((item) => {
        return item.state == "执行中";
      });
      if (!isHasComplete) {
        this.$message.warning("只有执行中的任务才能进行完成操作，请检查并重新勾选");
        return;
      }
      this.$confirm("是否将选中的任务完成, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [];
        ids = this.selectRecords.map((item) => {
          return item.id;
        });
        this.$server()
          .erdfRequest(`/server/${this.microservices}/base/${this.resource}/updateTaskState`, [ids, "complete"], "POST")
          .then(() => {
            this.$message.success("已完成");
            this.loadData();
            this.clearCheck();
          })
          .catch((response) => {
            this.$message.error(response.data.message);
          });
      });
    },
    // 删除任务
    deleteTasks() {
      this.selectRecords = this.$refs.table.getSelectRecords();
      if (this.selectRecords && this.selectRecords.length == 0) {
        this.$message.warning(this.$t("common.common_unselect_data"));
        return;
      }

      const isHasComplete = this.selectRecords.every((item) => {
        return item.state !== "待启动";
      });
      if (!isHasComplete) {
        this.$message.warning("启动之后的任务不能进行删除操作，请重新勾选");
        return;
      }
      this.$confirm("是否将选中的任务删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let ids = [];
        ids = this.selectRecords.map((item) => {
          return item.id;
        });
        this.$server()
          .erdfRequest(`/server/${this.microservices}/base/${this.resource}/deleteByTaskIds`, [ids], "POST")
          .then(() => {
            this.$message.success("删除成功");
            this.loadData();
            this.clearCheck();
          })
          .catch((response) => {
            this.$message.error(response.data.message);
          });
      });
    },
    // 领用（receive）
    receive() {
      this.selectRecords = this.$refs.table.getSelectRecords();
      if (this.selectRecords && this.selectRecords.length == 0) {
        this.$message.warning(this.$t("common.common_unselect_data"));
        return;
      }
      let ids = [];
      ids = this.selectRecords.map((item) => {
        return item.id;
      });
      this.$server()
        .erdfRequest(`/server/${this.microservices}/base/${this.resource}/assignResponsibleUser`, [ids, null], "post")
        .then(() => {
          this.$message.success("领用成功");
          this.loadData();
          this.clearCheck();
        })
        .catch((err) => {
          this.$message.error(err.data.message);
        });
    },
    // 指派
    distribution() {
      this.selectRecords = this.$refs.table.getSelectRecords();
      if (this.selectRecords && this.selectRecords.length == 0) {
        this.$message.warning(this.$t("common.common_unselect_data"));
        return;
      }
      this.$refs.personReceive.open();
    },
    personSelectBack(res) {
      let ids = [];
      ids = this.selectRecords.map((item) => {
        return item.id;
      });
      let userIds = [];
      userIds = res.map((item) => {
        return item.id;
      });
      this.$server()
        .erdfRequest(
          `/server/${this.microservices}/base/${this.resource}/assignResponsibleUser`,
          [ids, userIds],
          "post"
        )
        .then(() => {
          this.$message.success("指派成功");
          this.loadData();
          this.clearCheck();
        })
        .catch((err) => {
          this.$message.error(err.data.message);
        });
    },
  },
};
</script>
  <style lang="scss" scoped>
.search-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item {
    width: 32%;
    margin-right: 1%;
    margin-bottom: 10px;
  }
}

.custom-progress-text ::v-deep .el-progress__text {
  font-size: 12px !important; /* 替换为您想要的字体大小 */
}
</style>